package com.fz.song.myspring.spring;


import com.fz.song.myspring.songfazhun.Scope;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class SongFaZhunApplicationContext {

    /**
     * BeanDefinition集合,装的是bean的定义是一个map
     */
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    /**
     * 单例bean集合,装的是初始化好的单例的bean,是一个map
     */
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
    /**
     * BeanPostProcessor集合,bean的后置处理器,是一个list,
     * 所有的bean初始化完成后,都会调用这里面所有后置处理器的postProcessBeforeInitialization方法和postProcessAfterInitialization方法,
     * 我们不单单可是实现我们自己的业务,spring的很多特性也都是通过这个BeanPostProcessor实现的,例如aop
     */
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();


    public SongFaZhunApplicationContext(Class configClass) {
        //根据配置类扫描自定义代码
        scan(configClass);

        //实例化单例bena
        instanceSingletonBean();
    }

    /**
     * 实例化单例bena
     */
    private void instanceSingletonBean() {


        for (String beanName : beanDefinitionMap.keySet()) {
            //循环遍历所有的bean定义,
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            //判断是否是单例的bean
            if (beanDefinition.getScope().equals(ScopeEnum.singleton)) {
                //是单例的,则创建
                Object bean = doCreateBean(beanName, beanDefinition);
                //把创建好的单例bean添加到singletonObjects中
                singletonObjects.put(beanName, bean);
            }
        }

    }


    /**
     * 创建bean
     *
     * @param beanName
     * @param beanDefinition
     * @return
     */
    private Object doCreateBean(String beanName, BeanDefinition beanDefinition) {
        //根据bean定义获取bean 的class
        Class beanClass = beanDefinition.getBeanClass();
        try {
            //获取声明的构造方法
            Constructor constructor = beanClass.getDeclaredConstructor();
            //创建实例
            Object instance = constructor.newInstance();
            //获取该class的所有的属性
            Field[] fields = beanClass.getDeclaredFields();
            for (Field field : fields) {
                //遍历所有的属性,检查是否有Autowired注解
                if (field.isAnnotationPresent(Autowired.class)) {
                    //获取属性名字,
                    String fieldName = field.getName();
                    //获取bean
                    Object bean = getBean(fieldName);
                    //权限开启
                    field.setAccessible(true);
                    //赋值
                    field.set(instance, bean);
                }
            }

            // Aware回调,如果这个bean实现了BeanNameAware借口就强转成BeanNameAware对象,调用的他的setBeanName方法
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            //前置处理,
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(beanName, instance);
            }

            // 初始化
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }

            //后置处理
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                //注意后置处理如果被aop拦截了,返回的是一个代理对象
                instance = beanPostProcessor.postProcessAfterInitialization(beanName, instance);
            }
            //最后返回这个示例
            return instance;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 扫描代码
     *
     * @param configClass
     */
    private void scan(Class configClass) {
        //得到配置类的ComponentScan注解
        ComponentScan componentScan = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
        //获取componentScan注解中的值.得到需要扫描包的地址
        String packagePath = componentScan.value();
        System.out.println("spring 启动扫描地址:" + packagePath);
        //根据包地址获取扫描到的class集合
        List<Class> classList = getBeanClass(packagePath);
        for (Class clazz : classList) {
            if (clazz.isAnnotationPresent(Component.class)) {
                BeanDefinition definition = new BeanDefinition();
                definition.setBeanClass(clazz);

                //获取benaname
                Component component = (Component) clazz.getAnnotation(Component.class);
                String beanName = component.value();

                //当前类是不是BeanPostProcessor的子类
                if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                    try {
                        BeanPostProcessor instance = (BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
                        beanPostProcessorList.add(instance);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
                // 解析scope
                if (clazz.isAnnotationPresent(Scope.class)) {
                    Scope scope = (Scope) clazz.getAnnotation(Scope.class);
                    String scopeValue = scope.value();
                    if (ScopeEnum.singleton.name().equals(scopeValue)) {
                        definition.setScope(ScopeEnum.singleton);
                    } else {
                        definition.setScope(ScopeEnum.prototype);
                    }
                } else {
                    definition.setScope(ScopeEnum.singleton);
                }
                beanDefinitionMap.put(beanName, definition);
            }
        }
    }

    /**
     * 根据包地址获取扫描到的class集合
     *
     * @param packagePath
     * @return
     */
    private List<Class> getBeanClass(String packagePath) {
        List<Class> beanClasses = new ArrayList<>();
        ClassLoader classLoader = SongFaZhunApplicationContext.class.getClassLoader();
        packagePath = packagePath.replace(".", "/");
        URL resource = classLoader.getResource(packagePath);
        File file = new File(resource.getFile());

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                String fileName = f.getAbsolutePath();
                if (fileName.endsWith(".class")) {
                    String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                    className = className.replace("\\", ".");
                    try {
                        Class<?> clazz = classLoader.loadClass(className);
                        beanClasses.add(clazz);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return beanClasses;
    }


    /**
     * 获取bean
     *
     * @param beanName
     * @return
     */
    public Object getBean(String beanName) {
        //如果在单例bean的map中找到了就使用这个bena
        if (singletonObjects.containsKey(beanName)) {
            return singletonObjects.get(beanName);
        } else {
            //没有找到的话就创建bena,这里其实就是一个递归
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            return doCreateBean(beanName, beanDefinition);
        }
    }
}
